import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

import userApi from '../api/user'
import storage from '../utils/auth'

export default new Vuex.Store({
  state: {
    token: storage.getToken() ? storage.getToken() : '',
    userInfo: storage.getUserInfo() ? storage.getUserInfo() : ''
  },
  mutations: {
    saveToken(state,token){
      state.token = token;
      storage.setToken(token)
    },
    saveUserInfo(state,userInfo){
      state.userInfo = userInfo;
      storage.setUserInfo(userInfo)
    },
  },
  actions: {
    login({commit},ruleForm){
      return new Promise((resolve,reject)=>{
        userApi.doLogin(ruleForm.username, ruleForm.password).then(response=>{
          if(response.data.flag){
            let token = response.data.data.token
            commit('saveToken',token)
          }
          resolve(response)
        }).catch(error=>{
          reject(error)
        })
      })
    },
    getUserInfo({commit}){
      return new Promise((resolve,reject)=>{
        userApi.getUserInfo().then(response=>{
          if(response.data.flag){
            let userInfo = response.data.data
            commit('saveUserInfo',userInfo)
          }
          resolve(response)
        }).catch(error=>{
          reject(error)
        })
      })
    }
  },
  modules: {
    
  },
});
